package com.example.sync.cas;

import com.example.sync.factory.UnsafeFactory;
import sun.misc.Unsafe;

/**
 * @author dl.chai
 * @version 1.0
 * @description: CASTest
 * @date 2023/4/14 14:44
 */

public class CASTest {
    public static void main(String[] args) {
        //有问题
        Entity entity = new Entity();

        Unsafe unsafe = UnsafeFactory.getUnsafe();

        long offset = UnsafeFactory.getFieldOffset(unsafe, Entity.class, "x");

        boolean successful;

        // 4个参数分别是：对象实例、字段的内存偏移量、字段期望值、字段新值
        successful = unsafe.compareAndSwapInt(entity, offset, 0, 3);
        System.out.println(successful + "\t" + entity.x);

        successful = unsafe.compareAndSwapInt(entity, offset, 3, 5);
        System.out.println(successful + "\t" + entity.x);

        successful = unsafe.compareAndSwapInt(entity, offset, 3, 8);
        System.out.println(successful + "\t" + entity.x);
    }
}
